package com.streamer.app

import android.app.Dialog
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.streamer.app.R
import com.streamer.app.adapter.LotterySelectionAdapter
import com.streamer.app.adapter.WinningRecordGroupAdapter
import com.streamer.app.adapter.PrizeAdapter
import com.streamer.app.bean.LotteryBean
import com.streamer.app.bean.WinningRecordBean
import com.streamer.app.bean.WinningRecordGroup
import com.streamer.app.bean.PrizeBean
import com.streamer.app.utils.api.ViewModel
import com.streamer.app.bean.LotteryListBean
import com.streamer.app.utils.ToastUtil

class LotteryActivity : BaseActivity() {

    private lateinit var tvTabSettings: TextView
    private lateinit var tvTabRecords: TextView
    private lateinit var viewTabIndicator: View
    private lateinit var viewTabIndicator2: View
    private lateinit var layoutSettings: LinearLayout
    private lateinit var layoutRecords: LinearLayout
    private lateinit var topNavigationBar: LinearLayout
    private lateinit var etLotteryName: TextView
    private lateinit var etMinutes: EditText
    private lateinit var etSeconds: EditText

    private var viewMode = ViewModel()
    private var currentPage = 1
    private var pageSize = 10
    private var mRoomId = ""

    // 抽奖选择相关
    private var lotterySelectionDialog: Dialog? = null
    private var lotterySelectionAdapter: LotterySelectionAdapter? = null
    private var selectedLottery: LotteryBean? = null

    // 中奖记录相关
    private lateinit var rvWinningRecords: RecyclerView
    private lateinit var layoutEmptyRecords: LinearLayout
    private var winningRecordAdapter: WinningRecordGroupAdapter? = null

    // 奖品列表相关
    private lateinit var rvPrizeList: RecyclerView
    private var prizeAdapter: PrizeAdapter? = null
    private var prizeList: MutableList<PrizeBean> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lottery)

        initViews()
        setupListeners()
        setupTopPadding()
        updateTabUI(0) // 默认显示抽奖设置tab
    }

    private fun initViews() {
        mRoomId = intent.getStringExtra("roomId").toString()

        tvTabSettings = findViewById(R.id.tv_tab_settings)
        tvTabRecords = findViewById(R.id.tv_tab_records)
        viewTabIndicator = findViewById(R.id.view_tab_indicator)
        viewTabIndicator2 = findViewById(R.id.view_tab_indicator2)
        layoutSettings = findViewById(R.id.layout_settings)
        layoutRecords = findViewById(R.id.layout_records)
        topNavigationBar = findViewById(R.id.top_navigation_bar)
        etLotteryName = findViewById(R.id.et_lottery_name)
        etMinutes = findViewById(R.id.et_minutes)
        etSeconds = findViewById(R.id.et_seconds)


        // 初始化中奖记录RecyclerView
        rvWinningRecords = findViewById(R.id.rv_winning_records)
        layoutEmptyRecords = findViewById(R.id.layout_empty_records)

        // 设置RecyclerView
        rvWinningRecords.layoutManager = LinearLayoutManager(this)
        winningRecordAdapter = WinningRecordGroupAdapter(mutableListOf())
        rvWinningRecords.adapter = winningRecordAdapter

        // 初始化奖品列表RecyclerView
        rvPrizeList = findViewById(R.id.rv_prize_list)
        rvPrizeList.layoutManager = LinearLayoutManager(this)
        prizeAdapter = PrizeAdapter()
        rvPrizeList.adapter = prizeAdapter

        // 设置返回按钮
        findViewById<View>(R.id.iv_back).setOnClickListener {
            finish()
        }

        // 设置发布按钮点击事件
        findViewById<TextView>(R.id.tv_publish).setOnClickListener {
            publishLottery()
        }

        // 设置抽奖选择点击事件
        etLotteryName.setOnClickListener {
            showLotterySelectionDialog()
        }

        // 设置抽奖选择输入框为不可编辑
        etLotteryName.isFocusable = false
        etLotteryName.isFocusableInTouchMode = false

        viewMode.DrawPushLV.observe(this@LotteryActivity) { result ->
            if (result != null) {
                ToastUtil.toastShortMessage("发布成功!")
            }
        }
        // 观察奖品列表数据
        viewMode.ListQueryLV.observe(this@LotteryActivity) { prizeList ->
            if (prizeList != null && prizeList.isNotEmpty()) {
                // 将DrawBean转换为PrizeBean
                val prizes = prizeList.map { drawBean ->
                    PrizeBean(
                        id = drawBean.prizeId.toString(),
                        name = drawBean.prizeName,
                        description = "房间ID: ${drawBean.roomId}, 重复: ${if (drawBean.repetition) "是" else "否"}",
                        quantity = drawBean.prizeNum
                    )
                }

                Log.d("PrizeList", "转换后的奖品列表: ${prizes.size} 个奖品")
                // 更新UI显示奖品列表
                updatePrizeList(prizes)
            } else {
                Log.d("PrizeList", "API返回的奖品列表为空")
                // 清空奖品列表
                updatePrizeList(emptyList())
            }
        }
    }

    private fun publishLottery() {
        val lotteryName = etLotteryName.text.toString().trim()
        val minutesStr = etMinutes.text.toString().trim()
        val secondsStr = etSeconds.text.toString().trim()

        // 验证输入
        if (lotteryName.isEmpty() || lotteryName == "请选择抽奖") {
            Toast.makeText(this, "请选择抽奖", Toast.LENGTH_SHORT).show()
            return
        }

        val minutes = minutesStr.toIntOrNull() ?: 0
        val seconds = secondsStr.toIntOrNull() ?: 0

        if (minutes == 0 && seconds == 0) {
            Toast.makeText(this, "请设置开奖倒计时时间", Toast.LENGTH_SHORT).show()
            return
        }

        val totalSeconds = minutes * 60 + seconds
        val selectedLotteryId = selectedLottery?.id ?: ""
        viewMode.batchPush(mRoomId, selectedLottery?.id.toString(), totalSeconds)


        Log.d(
            "LotteryActivity",
            "发布抽奖 - ID: $selectedLotteryId, 名称: $lotteryName, 倒计时: ${totalSeconds}秒"
        )

        // 这里可以调用你的API
        // viewModel.publishLottery(selectedLotteryId, lotteryName, totalSeconds)
    }

    private fun setupTopPadding() {
        ViewCompat.setOnApplyWindowInsetsListener(topNavigationBar) { view, insets ->
            val statusBarHeight = insets.getInsets(WindowInsetsCompat.Type.statusBars()).top
            val basePadding = 0 // 顶部导航栏不需要额外padding
            val totalTopPadding = basePadding + statusBarHeight
            view.setPadding(
                view.paddingLeft, totalTopPadding, view.paddingRight, view.paddingBottom
            )
            insets
        }
    }

    private fun setupListeners() {
        tvTabSettings.setOnClickListener {
            updateTabUI(0)
        }

        tvTabRecords.setOnClickListener {
            updateTabUI(1)
        }
    }

    private fun updateTabUI(selectedTab: Int) {
        if (selectedTab == 0) {
            // 抽奖设置tab激活
            tvTabSettings.setTextColor(getColor(R.color.black))
            tvTabSettings.textSize = 16f
            tvTabSettings.setTypeface(null, android.graphics.Typeface.BOLD)
            tvTabRecords.setTextColor(getColor(R.color.gray))
            tvTabRecords.textSize = 16f
            tvTabRecords.setTypeface(null, android.graphics.Typeface.NORMAL)

            layoutSettings.visibility = View.VISIBLE
            layoutRecords.visibility = View.GONE

            // 显示第一个tab的指示器，隐藏第二个tab的指示器
            viewTabIndicator.visibility = View.VISIBLE
            viewTabIndicator2.visibility = View.GONE
        } else {
            // 中奖记录tab激活
            tvTabSettings.setTextColor(getColor(R.color.gray))
            tvTabSettings.textSize = 16f
            tvTabSettings.setTypeface(null, android.graphics.Typeface.NORMAL)
            tvTabRecords.setTextColor(getColor(R.color.black))
            tvTabRecords.textSize = 16f
            tvTabRecords.setTypeface(null, android.graphics.Typeface.BOLD)

            layoutSettings.visibility = View.GONE
            layoutRecords.visibility = View.VISIBLE

            // 隐藏第一个tab的指示器，显示第二个tab的指示器
            viewTabIndicator.visibility = View.GONE
            viewTabIndicator2.visibility = View.VISIBLE

            // 调用接口获取中奖记录数据
            viewMode.getRoomDrawUserList(mRoomId)

            // 加载中奖记录数据
            loadWinningRecords()
        }
    }

    private fun showLotterySelectionDialog() {
        if (lotterySelectionDialog == null) {
            lotterySelectionDialog = Dialog(this)
            lotterySelectionDialog?.setContentView(R.layout.dialog_lottery_selection)
            lotterySelectionDialog?.window?.setLayout(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
            )

            setupLotterySelectionDialog()
        }

        // 加载抽奖数据
        loadLotteryData()
        lotterySelectionDialog?.show()
    }

    private fun setupLotterySelectionDialog() {
        val dialog = lotterySelectionDialog ?: return

        // 初始化RecyclerView
        val rvLotteryList = dialog.findViewById<RecyclerView>(R.id.rv_lottery_list)
        rvLotteryList.layoutManager = LinearLayoutManager(this)

        // 初始化适配器
        lotterySelectionAdapter = LotterySelectionAdapter(mutableListOf()) { lottery ->
            selectedLottery = lottery
        }
        rvLotteryList.adapter = lotterySelectionAdapter

        // 搜索功能
        val etSearch = dialog.findViewById<EditText>(R.id.et_search_lottery)
        etSearch.setOnEditorActionListener { _, _, _ ->
            val query = etSearch.text.toString().trim()
            lotterySelectionAdapter?.filterLotteries(query)
            true
        }

        // 取消按钮
        dialog.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            lotterySelectionDialog?.dismiss()
        }

        // 确定按钮
        dialog.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
            val selected = lotterySelectionAdapter?.getSelectedLottery()
            if (selected != null) {
                selectedLottery = selected
                etLotteryName.setText(selected.name)

                // 选中抽奖后，调用接口获取奖品列表
                Log.d("LotterySelection", "选中抽奖: ${selected.name}, ID: ${selected.id}")
                viewMode.listQuery(selected.id)

                lotterySelectionDialog?.dismiss()
            } else {
                Toast.makeText(this, "请选择一个抽奖", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun loadLotteryData() {
        // 调用API获取抽奖数据
        viewMode.drawPageQuery(mRoomId, pageSize, currentPage)

        // 观察API返回的数据
        viewMode.DrawListLV.observe(this@LotteryActivity) { result ->
            if (result != null && result != null && result.isNotEmpty()) {
                val lotteries = result.map { drawBean ->
                    LotteryBean(
                        id = drawBean.drawId.toString(),
                        name = drawBean.drawTitle,
                        description = "",
                    )
                }
                lotterySelectionAdapter?.updateData(lotteries)
            }
        }
    }

    private fun loadWinningRecords() {
        // 观察接口返回的数据（接口已在Tab切换时调用）
        viewMode.LotterListLV.observe(this@LotteryActivity) { result ->
            if (result != null && result.rows != null) {
                Log.d("WinningRecords", "API返回中奖记录: ${result.rows.size} 条")
                updateWinningRecords(result.rows)
            } else {
                Log.d("WinningRecords", "API返回中奖记录为空")
                updateWinningRecords(emptyList())
            }
        }
    }

    private fun updateWinningRecords(lotteryList: List<LotteryListBean>) {
        if (lotteryList.isEmpty()) {
            // 显示空状态
            updateEmptyState()
            return
        }

        Log.d("WinningRecords", "开始处理 ${lotteryList.size} 条抽奖数据")

        // 将LotteryListBean转换为WinningRecordGroup
        val winningGroups = mutableListOf<WinningRecordGroup>()

        lotteryList.forEach { lotteryBean ->
            Log.d(
                "WinningRecords",
                "处理抽奖: ${lotteryBean.drawTitle}, 总参与人数: ${lotteryBean.data.size}"
            )

            // 过滤出中奖者（isWinners > 0）
            val winners = lotteryBean.data.filter { it.isWinners > 0 }
            Log.d("WinningRecords", "中奖者数量: ${winners.size}")

            // 打印所有参与者的isWinners状态
            lotteryBean.data.forEach { participant ->
                Log.d(
                    "WinningRecords",
                    "参与者: ${participant.nickName}, isWinners: ${participant.isWinners}"
                )
            }

            if (winners.isNotEmpty()) {
                // 将中奖者数据转换为WinningRecordBean
                val winningRecords = winners.map { winner ->
                    WinningRecordBean(
                        id = winner.drawId,
                        lotteryName = lotteryBean.drawTitle,
                        winnerName = winner.nickName ?: "未知用户",
                        prizeName = winner.prizeName ?: "未知奖品", // 提供默认值
                        winTime = winner.createTime ?: "",
                        status = "已发放"
                    )
                }

                // 创建分组
                val group = WinningRecordGroup(
                    releaseTime = lotteryBean?.createTime?:"", records = winningRecords
                )

                winningGroups.add(group)
                Log.d(
                    "WinningRecords",
                    "添加分组: ${lotteryBean.drawTitle}, 中奖记录数: ${winningRecords.size}"
                )
            } else {
                Log.d("WinningRecords", "抽奖 ${lotteryBean.drawTitle} 没有中奖者")
            }
        }

        // 更新适配器
        winningRecordAdapter?.updateGroups(winningGroups)
        updateEmptyState()

        Log.d("WinningRecords", "转换后的中奖记录分组: ${winningGroups.size} 个分组")
    }

    private fun updateEmptyState() {
        val recordCount = winningRecordAdapter?.itemCount ?: 0
        if (recordCount == 0) {
            layoutEmptyRecords.visibility = View.VISIBLE
            rvWinningRecords.visibility = View.GONE
        } else {
            layoutEmptyRecords.visibility = View.GONE
            rvWinningRecords.visibility = View.VISIBLE
        }
    }

    // 动态添加中奖记录的方法（供外部调用）
    fun addWinningRecord(record: WinningRecordBean) {
        // 添加到最新的分组中，如果没有分组则创建新分组
        val currentTime = "2025-03-02 12:12:12" // 这里应该获取当前时间
        val newGroup = WinningRecordGroup(currentTime, listOf(record))
        winningRecordAdapter?.addGroup(newGroup)
        updateEmptyState()
    }

    // 批量添加中奖记录的方法
    fun addWinningRecords(records: List<WinningRecordBean>) {
        // 按时间分组添加
        val currentTime = "2025-03-02 12:12:12" // 这里应该获取当前时间
        val newGroup = WinningRecordGroup(currentTime, records)
        winningRecordAdapter?.addGroup(newGroup)
        updateEmptyState()
    }

    // 添加测试中奖记录的方法
    private fun addTestWinningRecord() {
        val testRecord = WinningRecordBean(
            System.currentTimeMillis().toString(),
            "测试抽奖${System.currentTimeMillis() % 1000}",
            "测试用户${System.currentTimeMillis() % 100}",
            "测试奖品${System.currentTimeMillis() % 50}",
            "2024-01-${System.currentTimeMillis() % 30 + 1} ${System.currentTimeMillis() % 24}:${System.currentTimeMillis() % 60}:${System.currentTimeMillis() % 60}",
            "待发放"
        )

        addWinningRecord(testRecord)
        Toast.makeText(this, "已添加测试记录", Toast.LENGTH_SHORT).show()
    }

    // 更新奖品列表显示
    private fun updatePrizeList(newPrizeList: List<PrizeBean>) {
        Log.d("PrizeList", "updatePrizeList called with ${newPrizeList.size} items")
        Log.d("PrizeList", "prizeAdapter is null: ${prizeAdapter == null}")

        Log.d("PrizeList", "newPrizeList content: $newPrizeList")

        // 直接更新适配器，不需要中间列表
        prizeAdapter?.updatePrizes(newPrizeList)
        Log.d("PrizeList", "updatePrizes called, adapter itemCount: ${prizeAdapter?.itemCount}")
    }
} 